<template>
  <div class="todoapp">
    <todo-header
      @add="add"
      :list="list"
      @check="list.forEach(v => (v.isDone = $event))"
    />
    <todo-main :list="renderList" @del="del" />
    <todo-footer
      :count="renderList.length"
      @clear="clear"
      @check="type = $event"
    />
  </div>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoFooter from './components/TodoFooter.vue'
import TodoMain from './components/TodoMain.vue'
export default {
  components: {
    TodoHeader,
    TodoFooter,
    TodoMain
  },
  data () {
    return {
      list: JSON.parse(localStorage.getItem('list')) || 
      [
        { id: 100, name: '吃饭', isDone: true },
        { id: 201, name: '睡觉', isDone: false },
        { id: 103, name: '打豆豆', isDone: true }
      ],
      type: 'all'
    }
  },
  watch:{
    list:{
      deep: true,
      handler(){
        localStorage.setItem('list', JSON.stringify(this.list))
      }
    }
  },
  computed: {
    renderList () {
      if (this.type === 'all') {
        return this.list
      } else if (this.type === 'not') {
        return this.list.filter(v => !v.isDone)
      } else {
        return this.list.filter(v => v.isDone)
      }
    }
  },
  methods: {
    clear(){
      this.list = this.list.filter(v => !v.isDone)
    },
    del (id) {
      this.list = this.list.filter(v => v.id !== id)
    },
    add (name) {
      this.list.push({
        id: Date.now(),
        name,
        isDone: false
      })
    },

    all () {
      this.list
    }
  }
}
</script>

<style></style>
